<template>
  <BasicModal
    v-bind="$attrs"
    @register="userRegister"
    title="新增用户"
    :width="424"
    :minHeight="320"
    centered
    @ok="confirmSubmit"
    @cancel="resetModal"
  >
    <div class="add-user" v-loading="dataLoading">
      <div class="user-info">
        <info-circle-outlined
          :style="{
            fontSize: '24px',
            color: '#275EEA'
          }"
        />
        <div class="info-txt">
          手机号码/邮箱将作为用户账号，请选择进行填写，新建成功后，账号密码将发送至该手机号码/邮箱
        </div>
      </div>
      <div class="user-form">
        <div class="form-title">{{ modalInfo.selectCompany.orgName }}</div>
        <BasicForm @register="userForm" />
      </div>
    </div>
  </BasicModal>
</template>
<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { BasicModal, useModalInner } from '@/components/Modal'
import { BasicForm, FormSchema, useForm } from '@/components/Form/index'
import { cloneDeep } from 'lodash-es'
import { InfoCircleOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { pattern } from '@/utils/validate/index'
import dayjs, { Dayjs } from 'dayjs'
type RangeValue = [Dayjs, Dayjs]
import { toEleTreeData } from '@/utils'
import api from '@/api'

const emit = defineEmits(['operateSuccess', 'register'])

const { subEnterpriseList, enterpriseUserAdd } = api

const dataLoading = ref(false)
const modalInfo = reactive<any>({
  selectCompany: {},
  tenantId: ''
})
const ranges = {
  试用1天: [dayjs(), dayjs().add(1, 'day')] as RangeValue,
  试用30天: [dayjs(), dayjs().add(30, 'day')] as RangeValue,
  正式365天: [dayjs(), dayjs().add(365, 'day')] as RangeValue
}
// 选择当天之后时间
const disabledDate = (current: Dayjs) => {
  return current && current < dayjs().startOf('day')
}

const [userRegister, { setModalProps, changeOkLoading, closeModal }] = useModalInner(async (data) => {
  modalInfo.selectCompany = data.selectCompany || {}
  modalInfo.tenantId = data.tenantId
  dataLoading.value = true
  let tenantUserAuthFlag = modalInfo.selectCompany.tenantUserAuthFlag
  updateSchema([
    {
      field: '[authBeginDate, authEndDate]',
      ifShow: tenantUserAuthFlag == 1
    }
  ])
  try {
    let res = await subEnterpriseList({
      topTenantId: data.tenantId
    })
    dataLoading.value = false
    let treeDataList: any[] = toEleTreeData(res.result, { parentId: 'parentTenantId', id: 'tenantId' })
    updateSchema([
      {
        field: 'toTenantId',
        componentProps: {
          treeData: treeDataList
        }
      }
    ])
  } catch (error) {
    dataLoading.value = false
  }
})

const schemas: FormSchema[] = [
  {
    field: 'userName',
    component: 'Input',
    label: '姓名',
    required: true
  },
  {
    field: 'toTenantId',
    label: '所属企业',
    component: 'TreeSelect',
    componentProps: {
      fieldNames: {
        label: 'orgName',
        value: 'tenantId'
      }
    },
    required: true
  },
  {
    field: 'phoneNumber',
    component: 'Input',
    label: '手机号码',
    rules: [
      {
        pattern: pattern.regexp_cell_phone,
        message: '请输入正确的手机号码'
      }
    ]
  },
  {
    field: 'email',
    component: 'Input',
    label: '联系邮箱',
    rules: [
      {
        pattern: pattern.regexp_email,
        message: '请输入正确的联系邮箱'
      }
    ]
  },
  {
    field: '[authBeginDate, authEndDate]',
    component: 'RangePicker',
    label: '授权时间',
    rules: [
      {
        required: true,
        message: '请选择授权时间',
        trigger: 'change'
      }
    ],
    componentProps: {
      valueFormat: 'YYYY-MM-DD',
      getPopupContainer: () => document.body,
      ranges,
      disabledDate: disabledDate
    }
  }
]

const [userForm, { getFieldsValue, validate, resetFields, updateSchema }] = useForm({
  showActionButtonGroup: false,
  labelWidth: 70,
  schemas,
  baseColProps: {
    span: 24,
    style: {
      marginBottom: '4px'
    }
  }
})

const resetModal = () => {
  resetFields()
  changeOkLoading(false)
}

const confirmSubmit = async () => {
  try {
    await validate()
    let formValue = getFieldsValue()
    if (!formValue.email && !formValue.phoneNumber) {
      return message.error('联系邮箱和手机号码必须填写一项')
    }
    if (modalInfo.selectCompany.tenantUserAuthFlag == 1) {
      let currentDate = dayjs().format('YYYY-MM-DD')
      if (formValue.authBeginDate != currentDate) {
        return message.error('授权起始时间必须为当天')
      }
    }

    changeOkLoading(true)
    await enterpriseUserAdd({
      ...formValue
    })
    closeModal()
    changeOkLoading(false)
    resetModal()
    message.success('新增用户成功')
    emit('operateSuccess')
  } catch (error) {
    changeOkLoading(false)
  }
}
</script>
<style lang="less" scoped>
.add-user {
  .user-info {
    padding: 16px;
    background: #e9f4fe;
    border-radius: 2px;
    display: flex;
    margin-bottom: 30px;
    .info-txt {
      color: #192236;
      margin-left: 14px;
      line-height: 17px;
    }
  }
  .user-form {
    padding-right: 14px;
    padding-left: 32px;
    .form-title {
      font-size: 16px;
      font-weight: 600;
      color: #172237;
      line-height: 22px;
      margin-bottom: 16px;
      padding-left: 18px;
    }
  }
}
</style>
